package com.shao.intelligentsnake;

import java.util.function.Predicate;

/**
 * 有向探针
 *
 * @author shaohuailin
 * @date 2024/4/21
 */
public class DirectedProbe implements Probe {

    private int[] stateTable;
    private int size;

    public DirectedProbe(int[] stateTable, int size) {
        this.stateTable = stateTable;
        this.size = size;
    }

    @Override
    public int[] probe(int position) {
        int x = position >> 8 & 0xFF;
        int y = position & 0xFF;

        // 是否偶数
        boolean xEven = x % 2 == 0;
        boolean yEven = y % 2 == 0;

        int len = 0;
        boolean up = false, right = false, down = false, left = false;
        // 四个方向的位置
        int upPos = x << 8 | (y - 1), rightPos = (x + 1) << 8 | y,
                downPos = x << 8 | (y + 1), leftPos = (x - 1) << 8 | y;

        Predicate<Integer> viable = (n) ->
                stateTable[n] == GameParams.STATE_EMPTY || stateTable[n] == GameParams.STATE_FOOD;
        // 判断向四个方向能否行动
        if (y > 0 && xEven && viable.test(upPos)) {
            len++;
            up = true;
        }
        if (x + 1 < size && yEven && viable.test(rightPos)) {
            len++;
            right = true;
        }
        if (y + 1 < size && !xEven && viable.test(downPos)) {
            len++;
            down = true;
        }
        if (x > 0 && !yEven && viable.test(leftPos)) {
            len++;
            left = true;
        }

        int idx = 0;
        int[] res = new int[len];
        if (up) {
            res[idx++] = upPos;
        }
        if (right) {
            res[idx++] = rightPos;
        }
        if (down) {
            res[idx++] = downPos;
        }
        if (left) {
            res[idx] = leftPos;
        }
        return res;
    }
}
